package com.huzz.config;

import com.huzz.security.filter.JwtVerificationFilter;
import com.huzz.security.handler.CustAuthenticationEntryPoint;
import com.huzz.properties.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig {
    @Autowired
    private Properties properties;

    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
        return authenticationManager;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //禁用csrf保护机制
        http.csrf().disable();
        //禁用cors保护机制
        http.cors().disable();
        //禁用session会话
        http.sessionManagement().disable();
        //禁用form表单登录
        http.formLogin().disable();
        //增加自定义验证过滤器（资源服务需要配置）
        http.addFilter(new JwtVerificationFilter(authenticationManager(), properties));
        // 过滤请求
        http.authorizeRequests()
                .antMatchers("/doc.html", "/swagger-ui.html").permitAll()
                .antMatchers("/admin").hasRole("ADMIN")
                // .anyRequest().access("@defaultAccess.hasPermit(request,authentication)")
                .anyRequest().authenticated();
        // 认证失败处理器
        http.exceptionHandling().authenticationEntryPoint(new CustAuthenticationEntryPoint());

        http.headers().frameOptions().disable();

        return http.build();
    }
}